package com.atguigu.flink.day09;

import com.atguigu.flink.bean.WaterSensor;
import com.atguigu.flink.func.WaterSensorMapFunction;
import org.apache.flink.api.common.state.StateTtlConfig;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

/**
 * @author Felix
 * @date 2024/8/19
 * 该案例演示了状态的生存时间的设置
 */
public class Flink05_KeyedState_TTL {
    public static void main(String[] args) throws Exception {
        //TODO 1.环境准备
        //1.1 指定流处理环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        //1.2 设置并行度
        env.setParallelism(1);
        //TODO 2.从指定的网络端口读取数据
        DataStreamSource<String> socketDS = env.socketTextStream("hadoop102", 8888);
        //TODO 3.对流中数据进行类型转换    String->WaterSensor
        SingleOutputStreamOperator<WaterSensor> wsDS = socketDS.map(new WaterSensorMapFunction());
        //TODO 4.按照传感器id进行分组
        KeyedStream<WaterSensor, String> keyedDS = wsDS.keyBy(WaterSensor::getId);
        //TODO 5.判断连续的两个水位差值是否超过10
        keyedDS.process(
                new KeyedProcessFunction<String, WaterSensor, String>() {
                    //声明键控状态 注意：和普通变量作用范围不一样，键控状态的作用范围就是keyby后的每一个组
                    //注意：不能在声明的时候直接赋值，因为这个时候还获取不到运行时上下文
                    ValueState<Integer> lastVcState;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        //状态的赋值
                        ValueStateDescriptor<Integer> valueStateDescriptor
                                = new ValueStateDescriptor<>("lastVcState", Integer.class);
                        //注意：这里的时间指定是系统时间
                        valueStateDescriptor.enableTimeToLive(
                                StateTtlConfig
                                        .newBuilder(Time.seconds(10))
                                        //.setUpdateType(StateTtlConfig.UpdateType.OnCreateAndWrite)
                                        //.setUpdateType(StateTtlConfig.UpdateType.OnReadAndWrite)
                                        .setStateVisibility(StateTtlConfig.StateVisibility.NeverReturnExpired)
                                        .build());
                        lastVcState = getRuntimeContext().getState(valueStateDescriptor);

                    }

                    @Override
                    public void processElement(WaterSensor ws, KeyedProcessFunction<String, WaterSensor, String>.Context ctx, Collector<String> out) throws Exception {
                        //获取当前水位值
                        Integer curVc = ws.getVc();
                        //获取上次水位值
                        Integer lastVc = lastVcState.value()==null ?0:lastVcState.value();

                        if(Math.abs(curVc - lastVc) > 10){
                            out.collect("传感器"+ctx.getCurrentKey()+"当前水位"+curVc+"和上次水位"+lastVc+"之差大于10");
                        }
                        if(curVc < 30){
                            //更新当前水位值到状态中
                            lastVcState.update(curVc);
                        }
                    }
                }
        ).printToErr();


        env.execute();

    }
}
